package otSpaces.util;

import java.io.Serializable;
import java.util.HashMap;

public class IdTable implements Serializable {

	private static final long serialVersionUID = -3167111301906666298L;
	private final ShortFactory _idFactory = new ShortFactory();

	private final HashMap<Short, String> _idMap = new HashMap<Short, String>();

	private final HashMap<String, Short> _nameMap = new HashMap<String, Short>();

	public boolean contains(short id) {
		return _idMap.containsKey(id);
	}

	public boolean contains(String name) {
		return _nameMap.containsKey(name);
	}

	public String get(short id) {
		return _idMap.get(id);
	}

	public short get(String name) {
		return _nameMap.get(name);
	}

	private short getNextId() {
		final short next = _idFactory.next();

		if (contains(next)) {
			return getNextId();
		} else {
			return next;
		}
	}

	public String remove(short id) {
		assert contains(id);

		final String ret = _idMap.remove(id);

		_nameMap.remove(ret);

		return ret;
	}

	public short remove(String name) {
		assert contains(name);

		final short ret = _nameMap.remove(name);

		_idMap.remove(ret);

		return ret;
	}

	public void set(short id, String name) {
		_idMap.put(id, name);
		_nameMap.put(name, id);
	}

	public short set(String name) {
		final short id = getNextId();

		set(id, name);

		return id;
	}

}
